<template>
  <div class="effect-evaluation">
    <!-- 面包屑导航 -->
    <a-breadcrumb class="breadcrumb">
      <a-breadcrumb-item>
        <router-link to="/salvation">超度与救赎</router-link>
      </a-breadcrumb-item>
      <a-breadcrumb-item>
        <router-link to="/salvation/transcendence-application">超度申请管理</router-link>
      </a-breadcrumb-item>
      <a-breadcrumb-item>效果评估</a-breadcrumb-item>
    </a-breadcrumb>

    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="page-title">效果评估</div>
        <div class="page-subtitle">评估超度仪式的效果和成功率</div>
      </div>
      <div class="header-actions">
        <a-button type="primary">
          <LineChartOutlined />
          生成报告
        </a-button>
      </div>
    </div>

    <!-- 评估统计 -->
    <div class="evaluation-stats">
      <a-row :gutter="[20, 20]">
        <a-col :xs="12" :sm="6" :lg="6">
          <div class="stat-card">
            <div class="stat-icon">
              <CheckCircleOutlined />
            </div>
            <div class="stat-content">
              <div class="stat-value">87.5%</div>
              <div class="stat-label">成功率</div>
            </div>
          </div>
        </a-col>
        <a-col :xs="12" :sm="6" :lg="6">
          <div class="stat-card">
            <div class="stat-icon">
              <TrophyOutlined />
            </div>
            <div class="stat-content">
              <div class="stat-value">156</div>
              <div class="stat-label">成功案例</div>
            </div>
          </div>
        </a-col>
        <a-col :xs="12" :sm="6" :lg="6">
          <div class="stat-card">
            <div class="stat-icon">
              <ClockCircleOutlined />
            </div>
            <div class="stat-content">
              <div class="stat-value">23</div>
              <div class="stat-label">待评估</div>
            </div>
          </div>
        </a-col>
        <a-col :xs="12" :sm="6" :lg="6">
          <div class="stat-card">
            <div class="stat-icon">
              <StarOutlined />
            </div>
            <div class="stat-content">
              <div class="stat-value">4.8</div>
              <div class="stat-label">平均评分</div>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 效果评估表 -->
    <div class="evaluation-list">
      <div class="list-header">
        <h3>效果评估记录</h3>
        <div class="header-actions">
          <a-input-search placeholder="搜索仪式或亡魂姓名" style="width: 300px" @search="handleSearch" />
          <a-select v-model:value="statusFilter" placeholder="评估状态" style="width: 120px; margin-left: 12px" @change="handleFilterChange">
            <a-select-option value="">全部状态</a-select-option>
            <a-select-option value="已评估">已评估</a-select-option>
            <a-select-option value="待评估">待评估</a-select-option>
            <a-select-option value="评估中">评估中</a-select-option>
          </a-select>
        </div>
      </div>

      <a-table :columns="columns" :data-source="filteredEvaluations" :pagination="pagination" row-key="id">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ record.status }}
            </a-tag>
          </template>
          <template v-if="column.key === 'effectiveness'">
            <a-progress :percent="record.effectiveness" size="small" :stroke-color="getEffectivenessColor(record.effectiveness)" />
          </template>
          <template v-if="column.key === 'rating'">
            <a-rate :value="record.rating" disabled style="font-size: 14px" />
            <span style="margin-left: 8px; color: rgba(255, 255, 255, 0.8)">
              {{ record.rating.toFixed(1) }}
            </span>
          </template>
          <template v-if="column.key === 'soulCondition'">
            <a-tag :color="getSoulConditionColor(record.soulCondition)">
              {{ record.soulCondition }}
            </a-tag>
          </template>
          <template v-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" size="small" @click="viewDetail(record)"> 查看详情 </a-button>
              <a-button type="link" size="small" @click="evaluate(record)" :disabled="record.status === '已评估'"> 开始评估 </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 查看详情模态框 -->
    <a-modal v-model:open="showDetailModal" title="效果评估详情" width="1000px" :footer="null">
      <div class="evaluation-detail" v-if="selectedEvaluation">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-card class="detail-card">
              <h4>基本信息</h4>
              <a-descriptions :column="1" size="small">
                <a-descriptions-item label="评估编号">{{ selectedEvaluation.id }}</a-descriptions-item>
                <a-descriptions-item label="仪式编号">{{ selectedEvaluation.ritualId }}</a-descriptions-item>
                <a-descriptions-item label="亡魂姓名">{{ selectedEvaluation.soulName }}</a-descriptions-item>
                <a-descriptions-item label="仪式类型">
                  <a-tag :color="getTypeColor(selectedEvaluation.ritualType)">
                    {{ selectedEvaluation.ritualType }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="完成时间">{{ selectedEvaluation.completionDate }}</a-descriptions-item>
                <a-descriptions-item label="评估时间">{{ selectedEvaluation.evaluationDate || '待评估' }}</a-descriptions-item>
                <a-descriptions-item label="评估状态">
                  <a-tag :color="getStatusColor(selectedEvaluation.status)">
                    {{ selectedEvaluation.status }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="评估人员">{{ selectedEvaluation.evaluator || '待分配' }}</a-descriptions-item>
              </a-descriptions>
            </a-card>
          </a-col>

          <a-col :span="16">
            <a-card class="detail-card">
              <h4>效果评估</h4>
              <a-row :gutter="16">
                <a-col :span="12">
                  <div class="score-section">
                    <h5>效果评分</h5>
                    <a-progress type="circle" :percent="selectedEvaluation.effectiveness" :stroke-color="getEffectivenessColor(selectedEvaluation.effectiveness)" :size="80" />
                    <p>{{ selectedEvaluation.effectiveness }}% 有效</p>
                  </div>
                </a-col>
                <a-col :span="12">
                  <div class="rating-section">
                    <h5>综合评分</h5>
                    <div style="text-align: center">
                      <a-rate :value="selectedEvaluation.rating" disabled style="font-size: 24px" />
                      <p style="margin-top: 8px; font-size: 18px; font-weight: bold">{{ selectedEvaluation.rating.toFixed(1) }}/5.0</p>
                    </div>
                  </div>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
        </a-row>

        <a-card class="detail-card" style="margin-top: 16px">
          <h4>详细评估</h4>
          <a-row :gutter="16">
            <a-col :span="8">
              <div class="criterion-item">
                <h5>亡魂状态</h5>
                <a-tag :color="getSoulConditionColor(selectedEvaluation.soulCondition)" size="large">
                  {{ selectedEvaluation.soulCondition }}
                </a-tag>
                <a-progress :percent="selectedEvaluation.soulProgress || 0" size="small" :stroke-color="getEffectivenessColor(selectedEvaluation.soulProgress || 0)" style="margin-top: 8px" />
              </div>
            </a-col>
            <a-col :span="8">
              <div class="criterion-item">
                <h5>仪式效果</h5>
                <div class="effect-indicators">
                  <div class="indicator">
                    <span>灵魂净化:</span>
                    <a-progress :percent="selectedEvaluation.purificationRate || 0" size="small" />
                  </div>
                  <div class="indicator">
                    <span>执念消除:</span>
                    <a-progress :percent="selectedEvaluation.obsessionRemoval || 0" size="small" />
                  </div>
                  <div class="indicator">
                    <span>轮回引导:</span>
                    <a-progress :percent="selectedEvaluation.reincarnationGuidance || 0" size="small" />
                  </div>
                </div>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="criterion-item">
                <h5>家属反馈</h5>
                <div class="feedback-section">
                  <a-rate :value="selectedEvaluation.familyRating || 0" disabled />
                  <p>{{ selectedEvaluation.familyFeedback || '暂无反馈' }}</p>
                </div>
              </div>
            </a-col>
          </a-row>
        </a-card>

        <a-card class="detail-card" style="margin-top: 16px">
          <h4>评估备注</h4>
          <p>{{ selectedEvaluation.notes || '暂无备注' }}</p>
        </a-card>

        <a-card class="detail-card" style="margin-top: 16px" v-if="selectedEvaluation.recommendations">
          <h4>改进建议</h4>
          <ul>
            <li v-for="(rec, index) in selectedEvaluation.recommendations" :key="index">
              {{ rec }}
            </li>
          </ul>
        </a-card>
      </div>
    </a-modal>

    <!-- 开始评估模态框 -->
    <a-modal v-model:open="showEvaluationModal" title="效果评估" width="800px" @ok="submitEvaluation" :confirmLoading="saving">
      <a-form :model="evaluationForm" layout="vertical" v-if="selectedEvaluation">
        <a-form-item label="评估信息">
          <a-input :value="`${selectedEvaluation.soulName} - ${selectedEvaluation.ritualType}`" disabled />
        </a-form-item>

        <a-form-item label="亡魂状态" required>
          <a-radio-group v-model:value="evaluationForm.soulCondition">
            <a-radio value="已超度">已超度</a-radio>
            <a-radio value="部分超度">部分超度</a-radio>
            <a-radio value="未超度">未超度</a-radio>
            <a-radio value="需要二次仪式">需要二次仪式</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="灵魂净化率" required>
              <a-slider v-model:value="evaluationForm.purificationRate" :min="0" :max="100" />
              <div style="text-align: center; margin-top: 8px">{{ evaluationForm.purificationRate }}%</div>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="执念消除率" required>
              <a-slider v-model:value="evaluationForm.obsessionRemoval" :min="0" :max="100" />
              <div style="text-align: center; margin-top: 8px">{{ evaluationForm.obsessionRemoval }}%</div>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="轮回引导效果" required>
              <a-slider v-model:value="evaluationForm.reincarnationGuidance" :min="0" :max="100" />
              <div style="text-align: center; margin-top: 8px">{{ evaluationForm.reincarnationGuidance }}%</div>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="综合评分" required>
              <a-rate v-model:value="evaluationForm.rating" allow-half />
              <span style="margin-left: 8px">{{ evaluationForm.rating }}/5</span>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="家属反馈评分">
          <a-rate v-model:value="evaluationForm.familyRating" allow-half />
          <span style="margin-left: 8px">{{ evaluationForm.familyRating }}/5</span>
        </a-form-item>

        <a-form-item label="家属反馈内容">
          <a-textarea v-model:value="evaluationForm.familyFeedback" :rows="2" placeholder="记录家属对仪式效果的反馈" />
        </a-form-item>

        <a-form-item label="评估备注" required>
          <a-textarea v-model:value="evaluationForm.notes" :rows="4" placeholder="请详细描述评估过程和结果" />
        </a-form-item>

        <a-form-item label="改进建议">
          <a-textarea v-model:value="evaluationForm.recommendationsText" :rows="3" placeholder="请提供改进建议（每行一条建议）" />
        </a-form-item>

        <a-form-item label="是否需要后续处理">
          <a-checkbox-group v-model:value="evaluationForm.followUpActions">
            <a-checkbox value="二次仪式">需要二次仪式</a-checkbox>
            <a-checkbox value="家属指导">家属心理指导</a-checkbox>
            <a-checkbox value="持续观察">持续观察</a-checkbox>
            <a-checkbox value="专业咨询">专业咨询</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useSalvationStore } from '@/stores/salvation'
import { LineChartOutlined, CheckCircleOutlined, TrophyOutlined, ClockCircleOutlined, StarOutlined } from '@ant-design/icons-vue'

const salvationStore = useSalvationStore()

// 筛选条件
const statusFilter = ref('')
const searchKeyword = ref('')

// 模态框状态
const showDetailModal = ref(false)
const showEvaluationModal = ref(false)
const selectedEvaluation = ref(null)
const saving = ref(false)

// 评估表单数据
const evaluationForm = ref({
  soulCondition: '已超度',
  purificationRate: 80,
  obsessionRemoval: 75,
  reincarnationGuidance: 85,
  rating: 4.5,
  familyRating: 4,
  familyFeedback: '',
  notes: '',
  recommendationsText: '',
  followUpActions: []
})

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `共 ${total} 条记录，第 ${range[0]}-${range[1]} 条`
})

// 模拟评估数据
const evaluationData = ref([
  {
    id: 'EE001',
    ritualId: 'RA001',
    soulName: '王老太',
    ritualType: '普通超度',
    completionDate: '2024-01-10',
    evaluationDate: '2024-01-12',
    status: '已评估',
    effectiveness: 92,
    rating: 4.8,
    soulCondition: '已超度',
    evaluator: '观音使者',
    notes: '仪式效果显著，亡魂安详离世',
    purificationRate: 92,
    obsessionRemoval: 88,
    reincarnationGuidance: 95,
    familyRating: 5,
    familyFeedback: '非常感谢，我们能感受到父亲的安详',
    recommendations: ['继续维护仪式质量', '加强家属后续关怀']
  },
  {
    id: 'EE002',
    ritualId: 'RA002',
    soulName: '李大爷',
    ritualType: '紧急超度',
    completionDate: '2024-01-12',
    evaluationDate: '',
    status: '待评估',
    effectiveness: 0,
    rating: 0,
    soulCondition: '评估中',
    evaluator: '',
    notes: ''
  },
  {
    id: 'EE003',
    ritualId: 'RA003',
    soulName: '张三',
    ritualType: '特殊超度',
    completionDate: '2024-01-08',
    evaluationDate: '2024-01-10',
    status: '已评估',
    effectiveness: 75,
    rating: 4.2,
    soulCondition: '部分超度',
    evaluator: '地藏使者',
    notes: '需要二次仪式加强效果',
    purificationRate: 75,
    obsessionRemoval: 70,
    reincarnationGuidance: 80,
    familyRating: 4,
    familyFeedback: '希望能继续帮助',
    recommendations: ['安排二次仪式', '加强执念清除', '提供家属指导']
  }
])

// 表格列配置
const columns = [
  {
    title: '评估编号',
    dataIndex: 'id',
    key: 'id',
    width: 100
  },
  {
    title: '亡魂姓名',
    dataIndex: 'soulName',
    key: 'soulName',
    width: 120
  },
  {
    title: '仪式类型',
    dataIndex: 'ritualType',
    key: 'ritualType',
    width: 120
  },
  {
    title: '完成时间',
    dataIndex: 'completionDate',
    key: 'completionDate',
    width: 120
  },
  {
    title: '评估状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '效果程度',
    dataIndex: 'effectiveness',
    key: 'effectiveness',
    width: 120
  },
  {
    title: '综合评分',
    dataIndex: 'rating',
    key: 'rating',
    width: 150
  },
  {
    title: '亡魂状态',
    dataIndex: 'soulCondition',
    key: 'soulCondition',
    width: 120
  },
  {
    title: '评估人',
    dataIndex: 'evaluator',
    key: 'evaluator',
    width: 100
  },
  {
    title: '操作',
    key: 'actions',
    width: 160
  }
]

// 过滤后的评估列表
const filteredEvaluations = computed(() => {
  let result = evaluationData.value

  // 状态筛选
  if (statusFilter.value) {
    result = result.filter((evaluation) => evaluation.status === statusFilter.value)
  }

  // 关键词搜索
  if (searchKeyword.value) {
    result = result.filter((evaluation) => evaluation.soulName.includes(searchKeyword.value) || evaluation.ritualId.includes(searchKeyword.value))
  }

  pagination.value.total = result.length
  return result
})

// 搜索处理
const handleSearch = (value) => {
  searchKeyword.value = value
}

// 筛选变更处理
const handleFilterChange = () => {
  pagination.value.current = 1
}

// 查看详情
const viewDetail = (record) => {
  selectedEvaluation.value = record
  showDetailModal.value = true
}

// 开始评估
const evaluate = (record) => {
  selectedEvaluation.value = record
  resetEvaluationForm()
  showEvaluationModal.value = true
}

// 重置评估表单
const resetEvaluationForm = () => {
  evaluationForm.value = {
    soulCondition: '已超度',
    purificationRate: 80,
    obsessionRemoval: 75,
    reincarnationGuidance: 85,
    rating: 4.5,
    familyRating: 4,
    familyFeedback: '',
    notes: '',
    recommendationsText: '',
    followUpActions: []
  }
}

// 提交评估
const submitEvaluation = async () => {
  try {
    saving.value = true

    // 处理改进建议文本转数组
    const recommendations = evaluationForm.value.recommendationsText ? evaluationForm.value.recommendationsText.split('\n').filter((item) => item.trim()) : []

    // 计算综合效果程度
    const effectiveness = Math.round((evaluationForm.value.purificationRate + evaluationForm.value.obsessionRemoval + evaluationForm.value.reincarnationGuidance) / 3)

    // 更新评估数据
    const updatedEvaluation = {
      ...selectedEvaluation.value,
      status: '已评估',
      effectiveness: effectiveness,
      rating: evaluationForm.value.rating,
      soulCondition: evaluationForm.value.soulCondition,
      evaluationDate: new Date().toISOString().split('T')[0],
      evaluator: '当前用户', // 这里应该从用户状态获取
      notes: evaluationForm.value.notes,
      purificationRate: evaluationForm.value.purificationRate,
      obsessionRemoval: evaluationForm.value.obsessionRemoval,
      reincarnationGuidance: evaluationForm.value.reincarnationGuidance,
      familyRating: evaluationForm.value.familyRating,
      familyFeedback: evaluationForm.value.familyFeedback,
      recommendations: recommendations,
      followUpActions: evaluationForm.value.followUpActions
    }

    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1500))

    // 更新本地数据
    const index = evaluationData.value.findIndex((item) => item.id === selectedEvaluation.value.id)
    if (index !== -1) {
      evaluationData.value[index] = updatedEvaluation
    }

    showEvaluationModal.value = false
    selectedEvaluation.value = null

    // 显示成功消息
    // notification.success({
    //   message: '评估完成',
    //   description: '效果评估已成功提交'
    // })
  } catch (error) {
    console.error('提交评估失败:', error)
    // notification.error({
    //   message: '提交失败',
    //   description: '评估提交失败，请重试'
    // })
  } finally {
    saving.value = false
  }
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colors = {
    已评估: 'success',
    待评估: 'warning',
    评估中: 'processing'
  }
  return colors[status] || 'default'
}

// 获取效果程度颜色
const getEffectivenessColor = (effectiveness) => {
  if (effectiveness >= 80) return '#52c41a'
  if (effectiveness >= 60) return '#1890ff'
  if (effectiveness >= 40) return '#faad14'
  return '#f5222d'
}

// 获取亡魂状态颜色
const getSoulConditionColor = (condition) => {
  const colors = {
    已超度: 'success',
    部分超度: 'warning',
    未超度: 'error',
    评估中: 'processing',
    需要二次仪式: 'processing'
  }
  return colors[condition] || 'default'
}

// 获取仪式类型颜色
const getTypeColor = (type) => {
  const colors = {
    普通超度: 'blue',
    紧急超度: 'orange',
    特殊超度: 'purple',
    VIP超度: 'gold'
  }
  return colors[type] || 'default'
}

onMounted(() => {
  console.log('效果评估页面已加载')
})
</script>

<style lang="scss" scoped>
.effect-evaluation {
  padding: 24px;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  min-height: 100vh;
  color: #fff;

  // 面包屑导航
  .breadcrumb {
    margin-bottom: 24px;

    :deep(.ant-breadcrumb-link) {
      color: rgba(255, 255, 255, 0.8);

      &:hover {
        color: #ffd700;
      }
    }

    :deep(.ant-breadcrumb-separator) {
      color: rgba(255, 255, 255, 0.6);
    }
  }

  // 页面头部
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;
    padding-bottom: 20px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .header-content {
      .page-title {
        font-size: 2rem;
        font-weight: bold;
        color: #fff;
        margin-bottom: 8px;
      }

      .page-subtitle {
        color: rgba(255, 255, 255, 0.8);
        font-size: 1rem;
      }
    }
  }

  // 评估统计
  .evaluation-stats {
    margin-bottom: 32px;

    .stat-card {
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.2);
      border-radius: 12px;
      padding: 20px;
      display: flex;
      align-items: center;
      gap: 16px;
      transition: all 0.3s ease;

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        background: rgba(255, 215, 0, 0.2);
        color: #ffd700;
      }

      .stat-content {
        .stat-value {
          font-size: 1.8rem;
          font-weight: bold;
          color: #fff;
          margin-bottom: 4px;
        }

        .stat-label {
          color: rgba(255, 255, 255, 0.8);
          font-size: 0.9rem;
        }
      }
    }
  }

  // 评估列表
  .evaluation-list {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    padding: 24px;

    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      padding-bottom: 12px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      h3 {
        margin: 0;
        color: #fff;
        font-size: 1.2rem;
      }

      .header-actions {
        display: flex;
        align-items: center;
      }
    }

    :deep(.ant-table) {
      background: transparent;

      .ant-table-thead > tr > th {
        background: rgba(255, 255, 255, 0.1);
        color: rgba(255, 255, 255, 0.9);
        border-bottom: 1px solid rgba(255, 255, 255, 0.2);
      }

      .ant-table-tbody > tr > td {
        background: transparent;
        color: rgba(255, 255, 255, 0.8);
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      }

      .ant-table-tbody > tr:hover > td {
        background: rgba(255, 255, 255, 0.05);
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .effect-evaluation {
    padding: 16px;

    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .header-content .page-title {
        font-size: 1.5rem;
      }
    }

    .stat-card {
      flex-direction: column;
      text-align: center;
      gap: 12px;

      .stat-content .stat-value {
        font-size: 1.5rem;
      }
    }

    .evaluation-list .list-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
    }
  }
}
</style>
